package com.adong.tv.data;

import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.adong.tv.model.Category;
import com.adong.tv.model.Movie;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 电影数据仓库
 */
public class MovieRepository {
    
    private static MovieRepository instance;
    private final ApiService apiService;
    
    private MovieRepository() {
        apiService = RetrofitClient.getApiService();
    }
    
    /**
     * 获取单例实例
     * @return MovieRepository实例
     */
    public static synchronized MovieRepository getInstance() {
        if (instance == null) {
            instance = new MovieRepository();
        }
        return instance;
    }
    
    /**
     * 刷新API服务（当API源变更时调用）
     */
    public void refreshApiService() {
        RetrofitClient.updateApiService();
    }
    
    /**
     * 获取电影列表
     * @param page 页码
     * @param categoryId 分类ID
     * @param keyword 搜索关键字
     * @return 包含电影列表的LiveData
     */
    public LiveData<ApiResult<List<Movie>>> getMovieList(int page, Integer categoryId, String keyword) {
        MutableLiveData<ApiResult<List<Movie>>> result = new MutableLiveData<>();
        
        // 调用API
        apiService.getMovieList("videolist", page, categoryId, keyword)
                .enqueue(new Callback<ApiResponse.ListResponse>() {
                    @Override
                    public void onResponse(Call<ApiResponse.ListResponse> call, Response<ApiResponse.ListResponse> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            ApiResponse.ListResponse data = response.body();
                            if (data.getCode() == 1 && data.getList() != null) {
                                result.setValue(ApiResult.success(data.getList()));
                            } else {
                                result.setValue(ApiResult.error("数据获取失败"));
                            }
                        } else {
                            result.setValue(ApiResult.error("网络请求失败"));
                        }
                    }
                    
                    @Override
                    public void onFailure(Call<ApiResponse.ListResponse> call, Throwable t) {
                        result.setValue(ApiResult.error("网络连接失败: " + t.getMessage()));
                    }
                });
        
        return result;
    }
    
    /**
     * 获取分类列表
     * @return 包含分类列表的LiveData
     */
    public LiveData<ApiResult<List<Category>>> getCategories() {
        MutableLiveData<ApiResult<List<Category>>> result = new MutableLiveData<>();
        
        // 调用API
        apiService.getMovieList("list", 1, null, null)
                .enqueue(new Callback<ApiResponse.ListResponse>() {
                    @Override
                    public void onResponse(Call<ApiResponse.ListResponse> call, Response<ApiResponse.ListResponse> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            ApiResponse.ListResponse data = response.body();
                            if (data.getCode() == 1 && data.getClasses() != null) {
                                Log.d("getCategories", "classes.size: " + data.getClasses().size());

                                List<Category> categories = new ArrayList<>();
                                for (Category item : data.getClasses()) {
                                    categories.add(new Category(item.getTypeId(), item.getTypePid(), item.getTypeName()));
                                }
                                result.setValue(ApiResult.success(categories));
                            } else {
                                result.setValue(ApiResult.error("分类获取失败"));
                            }

                        } else {
                            result.setValue(ApiResult.error("网络请求失败"));
                        }
                    }
                    
                    @Override
                    public void onFailure(Call<ApiResponse.ListResponse> call, Throwable t) {
                        result.setValue(ApiResult.error("网络连接失败: " + t.getMessage()));
                    }
                });
        
        return result;
    }

    /**
     * 获取搜索列表
     * @param page 页码
     * @param keyword 搜索关键字
     * @return 包含电影列表的LiveData
     */
    public LiveData<ApiResult<List<Movie>>> getSearchList(int page, String keyword) {
        MutableLiveData<ApiResult<List<Movie>>> result = new MutableLiveData<>();

        // 调用API
        apiService.getMovieDetail("videolist", 1, keyword)
                .enqueue(new Callback<ApiResponse.DetailResponse>() {
                    @Override
                    public void onResponse(Call<ApiResponse.DetailResponse> call, Response<ApiResponse.DetailResponse> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            ApiResponse.DetailResponse data = response.body();
                            if (data.getCode() == 1 && data.getList() != null) {
                                result.setValue(ApiResult.success(data.getList()));
                            } else {
                                result.setValue(ApiResult.error("数据获取失败"));
                            }
                        } else {
                            result.setValue(ApiResult.error("网络请求失败"));
                        }
                    }

                    @Override
                    public void onFailure(Call<ApiResponse.DetailResponse> call, Throwable t) {
                        result.setValue(ApiResult.error("网络连接失败: " + t.getMessage()));
                    }
                });

        return result;
    }
    
    /**
     * 获取电影详情
     * @param movieId 电影ID
     * @return 包含电影详情的LiveData
     */
    public LiveData<ApiResult<Movie>> getMovieDetail(int movieId) {
        MutableLiveData<ApiResult<Movie>> result = new MutableLiveData<>();
        
        // 调用API
        apiService.getMovieDetail("videolist", 1, String.valueOf(movieId))
                .enqueue(new Callback<ApiResponse.DetailResponse>() {
                    @Override
                    public void onResponse(Call<ApiResponse.DetailResponse> call, Response<ApiResponse.DetailResponse> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            ApiResponse.DetailResponse data = response.body();
                            if (data.getCode() == 1 && data.getList() != null && !data.getList().isEmpty()) {
                                Movie movie = data.getList().get(0);
                                
                                // 解析剧集列表
                                if (movie.getVodPlayUrl() != null && !movie.getVodPlayUrl().isEmpty()) {
                                    movie.setEpisodes(parseEpisodes(movie.getVodPlayUrl()));
                                }
                                
                                result.setValue(ApiResult.success(movie));
                            } else {
                                result.setValue(ApiResult.error("详情获取失败"));
                            }
                        } else {
                            result.setValue(ApiResult.error("网络请求失败"));
                        }
                    }
                    
                    @Override
                    public void onFailure(Call<ApiResponse.DetailResponse> call, Throwable t) {
                        result.setValue(ApiResult.error("网络连接失败: " + t.getMessage()));
                    }
                });
        
        return result;
    }
    
    /**
     * 解析剧集列表
     * @param playUrl 播放地址字符串，格式为: "1$url1#2$url2#3$url3"
     * @return 剧集列表
     */
    private List<Movie.Episode> parseEpisodes(String playUrl) {
        List<Movie.Episode> episodes = new ArrayList<>();
        
        String[] items = playUrl.split("#");
        for (String item : items) {
            String[] parts = item.split("\\$");
            if (parts.length == 2) {
                String name = "第" + parts[0] + "集";
                String url = parts[1];
                episodes.add(new Movie.Episode(name, url));
            }
        }
        
        return episodes;
    }
} 